package cn.chenwx.rabbitMQ;

import cn.chenwx.utils.MQConnectionUtils;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 工作队列——生产者
 */
public class Producer {

    /** 队列名称 */
    private static final String QUEUE_NAME = "test_queue2";

    public static void main(String[] args) throws IOException, TimeoutException {
        /** 1.获取连接 */
        Connection newConnection = MQConnectionUtils.newConnection();
         /** 2.创建通道 */
        Channel channel = newConnection.createChannel();
         /**3.创建队列声明 */
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
         /**保证一次只分发一次 限制发送给同一个消费者 不得超过一条消息 */
        channel.basicQos(1);
        for (int i = 1; i <= 10; i++) {
            String msg = "生产者消息_"+i ;
            System.out.println("生产者发送消息:" + msg);
            User user =new User();
            user.setId(10);
            user.setName("我是测试");

            System.out.println("发送消息："+user);
            /**4.发送消息 */
            channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,msg.getBytes());
        }
        channel.close();
        newConnection.close();
    }

}
